package com.newcapec.servlet;

import com.newcapec.bean.UserEntity;
import com.newcapec.service.SysUserService;
import com.newcapec.service.impl.SysUserServiceImpl;
import com.newcapec.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

/**
 * @Description:请求登录的servlet类
 * @Author:yangshupeng
 * @Date: 2022/3/21 22:43
 * @Version:1.0
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*//通知浏览器响应的内容类型
        resp.setContentType("text/html;charset=utf-8");*/
        //获取用户输入的验证码
        String code = req.getParameter("code");
        if (code != null){
            //获取程序中生成的验证码
            String validateCode = (String) req.getSession().getAttribute("validateCode");
            //和程序中生成的验证码进行比较
            if (!Objects.equals(code,validateCode)){
                //验证码错误
                resp.sendRedirect("login.html?type=5");
                return;
            }
        }else {
            resp.getWriter().write("no");
        }
        //获取登录表单提交的数据
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");


        //调用dao层的方法
        SysUserService sysUserService = new SysUserServiceImpl();

        if (userName != null && password != null) {
            password = MD5Util.toMD5(password);
            UserEntity userEntity = sysUserService.queryUserByAcct(userName);
            if (userEntity == null) {
                //账号不存在，重定向到登录界面，并传入一个参数做提示信息
                resp.sendRedirect("login.html?type=1");

            } else {
                //再比较密码是否相等
                if (Objects.equals(password, userEntity.getPwd())) {
                    //用户登录成功，跳转到系统主界面
                    //并将登录成功的用户信息保存到session对象
                    HttpSession session = req.getSession();
                    session.setAttribute("user", userEntity);
                    resp.sendRedirect("index.html");

                } else {
                    //密码错误
                    resp.sendRedirect("login.html?type=2");
                }
            }
        }else {
            resp.getWriter().write("no");
        }
    }
}
